<?php

namespace frontend\controllers;

use frontend\models\LogPayVip;
use frontend\models\UploadCertificate;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use frontend\models\PayTrade;
use yii\filters\AccessControl;
use frontend\models\LogPay;
use yii\web\UploadedFile;

class PayController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [
                            'pay-order',
                            'upload-certificate',
                            'pay-super-designer'
                        ],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    public function actionPayOrder()
    {
        $method = Yii::$app->request->post('pay-method');
        $segment = intval(Yii::$app->request->post('segment'));
        $trade_no = Yii::$app->request->post('trade_no');
        $order_info = PayTrade::findOne(['trade_no' => $trade_no, 'user_id' => Yii::$app->user->identity->id]);
        $item_data = json_decode($order_info["content"], true);
        $item_length = count($item_data);
        //查询每个单品判断是否需要询价
        $enquiry = 1;
        $t = 1;
        if (isset($item_data['coupon'])) {
            unset($item_data['coupon']);
        }
        foreach ($item_data as $type => $content) {
            foreach ($content as $index => $items) {
                foreach ($items['items'] as $item_index => $value) {
                    if ($t) {
                        $subject = $value['name'];
                        $t = 0;
                    }
                    if ($value['price_base'] <= 0) {
                        $enquiry = 0;
                        break;
                    }
                }
                if ($enquiry == 0) {
                    break;
                }
            }
            if ($enquiry == 0) {
                break;
            }
        }
        //如果已审核或不需要询价，则可以支付
        if ($order_info["audit_state"] || $enquiry) {
            //获取待支付的价格total_price
            //判断是否是分次付款
            $record = LogPay::find()->where(['trade_no' => $trade_no, 'uid' => Yii::$app->user->identity->id])->andWhere(['in', 'state', [1, 2]]);
            $trade_no_count = intval($record->max('trade_no_count'));
            if (!empty($record) && $trade_no_count == 1) {
                //此订单已进行过第一次付款,直接计算第二次需付款金额
                $total_price = $order_info["price_modify"] - $record->sum('rmb');
                $t_trade_no = $trade_no . "_2";
                $pay_count = 2;
            } elseif ($segment == 1) {
                //如果选择了分次付款的第一次
                $total_price = round($order_info["price_modify"] / 2, 2);
                $t_trade_no = $trade_no . "_1";
                $pay_count = 1;
            } else {
                //否则就是一次付清
                $total_price = $order_info["price_modify"];
                $t_trade_no = $trade_no;
                $pay_count = 1;
            }
            //商户订单号

            //订单名称subject
            $subject = $subject . ($item_length > 1 ? "等商品" : "");
            switch ($method) {
                case "alipay":
                    $this->alipay($total_price, $t_trade_no, $subject);
                    break;
                case "offlinepay":
                    return $this->Offlinepay($trade_no, $total_price, $pay_count);
                    break;
            }
//            return $this->render('alipay',[
//                't_trade_no' => $t_trade_no,
//                'subject' => $subject,
//                'total_price' => $total_price,
//            ]);
        } else {
            if ($enquiry <= 0) {
                echo "<div style='text-align:center;'>订单中含有待询价的产品，请联系客服改价。</div>";
            }
            if ($order_info["audit_state"] == 0) {
                echo "<div style='text-align:center;'>订单尚未审核，请等待客服联系，或在我的订单中查看</div>";
            }
        }
    }


    public function Offlinepay($trade_no, $total_price, $pay_count)
    {
        $model = new UploadCertificate();
        return $this->render('offlinepay', [
            'model' => $model,
            'trade_no' => $trade_no,
            'total_price' => $total_price,
            'pay_count' => $pay_count,
        ]);
    }

    public function actionUploadCertificate()
    {
        if (Yii::$app->request->isPost) {
            $out_trade_no = Yii::$app->request->post('trade_no');
            $order_price = Yii::$app->request->post('total_price');
            $pay_count = Yii::$app->request->post('pay_count');
            $uid = Yii::$app->user->id;
            if ($pay_count <= 0) {
                $pay_count = 1;
            }
            $ret = $this->pay_trade_state_check($out_trade_no, $uid, $order_price, $pay_count);
            if ($ret['status'] != 0) {
                return $this->render('submitSuccess',[
                    'ret' => $ret,
                    'redirectUrl' => Url::to(['account/order-list']),
                ]);
            }
            $one_trade = $ret['trade'];
            unset($ret['trade']);

            $model = new UploadCertificate();
            $account = Yii::$app->request->post('UploadCertificate')['account']; //银行账号
            $accountname = Yii::$app->request->post('UploadCertificate')['accountName']; //户名

            if ($model->load(Yii::$app->request->post())) {
                $model->certificate = UploadedFile::getInstanceByName("UploadCertificate[certificate]");
                if (empty($model->certificate)) {
                    $ret['status'] = -1;
                    $ret['message'] = '上传图片失败';
                    return $this->render('submitSuccess',[
                        'ret' => $ret,
                        'redirectUrl' => Url::to(['account/order-list']),
                    ]);
                }
                $newid = $model->upload();
                if (empty($newid)) {
                    $ret['status'] = -1;
                    $ret['message'] = '上传图片失败';
                    return $this->render('submitSuccess',[
                        'ret' => $ret,
                        'redirectUrl' => Url::to(['account/order-list']),
                    ]);
                }
            }
            $update_tf_trade_no = $out_trade_no . "_" . $pay_count . "_" . date("s", time());
            $prepay_id = "trans_$update_tf_trade_no";

            $xmlarr = array();
            $xmlarr['imageid'] = $newid;
            $xmlarr['account'] = $account;
            $xmlarr['accountName'] = $accountname;
            $memo_xml = json_encode($xmlarr, JSON_UNESCAPED_UNICODE);

            if ($this->create_pay_beforehand_order($uid, $prepay_id, 5, $out_trade_no, $pay_count, $memo_xml, $order_price) == false) {
                $ret['status'] = -1;
                $ret['message'] = '数据库操作失败';
                return $this->render('submitSuccess',[
                    'ret' => $ret,
                    'redirectUrl' => Url::to(['account/order-list']),
                ]);
            }

            $payTrade = PayTrade::findOne(['trade_no' => $out_trade_no]);
            $payTrade->trade_state = 9;
            if ($payTrade->save()) {
                return $this->render('submitSuccess',[
                    'ret' => $ret,
                    'redirectUrl' => Url::to(['account/order-list']),
                ]);
            }
        } else {
            return $this->redirect(['account/order-list']);
        }
    }
    // 生成与支付订单

    /**
     * uid    -- 支付用户,对应订单表的用户
     * prepay_id -- 订单唯一索引 - 微信为交易回话id , 支付宝为支付宝id (保证唯一)
     * type - 充值类型 1 - 微信 2 - 支付宝  5 - 转账
     * out_trade_no 我们订单表的订单号
     * pay_count   支付次数(多次支付的单子使用.)
     * memo_xml  -- 调用接口返回
     * order_price -- 预先支付的人民币(元)
     */
    public function create_pay_beforehand_order($uid, $prepay_id, $type, $out_trade_no, $pay_count, $memo_xml, $order_price)
    {
        $base_state = 0;
        if ($type == 5) {
            $base_state = 3;
        }
        $logPay = new LogPay();
        $logPay->prepay_id = $prepay_id;
        $logPay->transaction_id = $prepay_id;
        $logPay->trade_no = $out_trade_no;
        $logPay->trade_no_count = $pay_count;
        $logPay->uid = $uid;
        $logPay->type = $type;
        $logPay->starttime = time();
        $logPay->endtime = '0';
        $logPay->memo_xml = $memo_xml;
        $logPay->rmb = $order_price;
        $logPay->state = $base_state;
        $logPay->state_count = '0';
        $logPay->save();
        $save_tr_id = LogPay::find()->where(['prepay_id' => $prepay_id])->asArray()->one()['prepay_id'];
        if ($prepay_id != $save_tr_id) {
            return false;
        }
        return true;
    }

    // 用户订单状态检测,查看此订单是否可以支付
    private function pay_trade_state_check($out_trade_no, $uid, $order_price, $pay_count)
    {
        $ret = array();
        $ret['data'] = array();

        if (doubleval($order_price) <= 0) {
            $ret['status'] = -1;
            $ret['message'] = '支付的金额不能为0';
            return $ret;
        }

        $one_trade = PayTrade::find()->where(['trade_no' => $out_trade_no, 'user_id' => $uid])->one();
        //订单不存在
        if (empty($one_trade)) {
            $ret['status'] = -1;
            $ret['message'] = '订单错误';
            return $ret;
        }
        //订单状态错误
        switch (intval($one_trade['price_state'])) {
            case 0 : //0 代付款 可以继续付款
                break;
            case 11 : //11 已经部分付款
                break;
            case 1 :
                $ret['status'] = -1;
                $ret['message'] = '此订单您已经付款成功,不用再次付款';
                return $ret;
            case 2 :
                $ret['status'] = -1;
                $ret['message'] = "此订单为待退款状态,无法支付";
                return $ret;
            case 3 :
                $ret['status'] = -1;
                $ret['message'] = "此订单您已经退款,订单失效";
                return $ret;
            default :
                $ret['status'] = -1;
                $ret['message'] = '订单状态为非付款状态,无法付款';
                return $ret;
        }
        switch (intval($one_trade['trade_state'])) {
            case 0 :
                break;        // 0 - 待处理 , 可以支付
            case 1 :
                break;        // 1 - 已付款 			-- 只要钱没付完,都可以继续支付
            case 7 :
                break;        // 7 - 已发货(待收货)	-- 只要钱没付完,都可以继续支付
            case 9 :
                $ret['status'] = -1;
                $ret['message'] = "上次支付正在审核";
                return $ret;
            case 2 :
                $ret['status'] = -1;
                $ret['message'] = "此订单您已经取消,失效订单";
                return $ret;
            case 3 :
                $ret['status'] = -1;
                $ret['message'] = "此订单已经完成,无法支付";
                return $ret;
            case 4 :
                $ret['status'] = -1;
                $ret['message'] = "此订单正在退款中";
                return $ret;
            case 5 :
                $ret['status'] = -1;
                $ret['message'] = "此订单退款成功,订单关闭";
                return $ret;
            case 6 :
                $ret['status'] = -1;
                $ret['message'] = "请询价,请联系客服询问详细价格";
                return $ret;
            default :
                $ret['status'] = -1;
                $ret['message'] = '订单状态为非付款状态,无法付款';
                return $ret;
        }
        // 价格不能小于0
        if (doubleval($one_trade['price']) < 0) {
            $ret['status'] = -1;
            $ret['message'] = '价格不能为0';
            return $ret;
        }
        // 订单价格更改后必须经过审核才允许用户付钱.
        if (doubleval($one_trade['price']) != doubleval($one_trade['price_modify'])) {
            if (intval($one_trade['audit_state']) != 1) {
                $ret['status'] = -1;
                $ret['message'] = '订单修改价格未审核通过';
                return $ret;
            }
        }

        $price_now = 0;        // 已经支付的金额
        $trade_count = 0;        // 已经支付的次数
        $alltrade = LogPay::find()->where(['and', ['trade_no' => $out_trade_no,], ['in', 'state', [1, 2]]])->asArray()->all();
        if (is_array($alltrade)) {
            foreach ($alltrade as $at) {
                $price_now += doubleval($at['rmb']);
                $trade_count += 1;
            }
        }

        // 支付金额和汇总付款金额检测
        $money = doubleval($one_trade['price_modify']);        // 总共实际需要支付金额
        // 本次支付请求支付的金额  $order_price
        if ((doubleval($order_price) + $price_now) > $money) {
            $ret['status'] = -1;
            $ret['message'] = "支付的金额过多.";
            return $ret;
        }
        // 支付次数的检测
        if ($pay_count <= 0) {
            $pay_count = 1;
        }
        if ($pay_count - 1 != $trade_count) {
            $ret['status'] = -1;
            $ret['message'] = "分次支付次数错误";
            return $ret;
        }

        // 处理新订单,检测订单是否可支付
        $log_trade = LogPay::find()->where(['trade_no' => $out_trade_no, 'trade_no_count' => $pay_count])->asArray()->one();
        if (!empty($log_trade)) {
            if (intval($log_trade['state']) != 1 && intval($log_trade['state']) != 2) {
                // 删除作废的订单
                LogPay::findOne(['trade_no' => $out_trade_no, 'trade_no_count' => $pay_count])->delete();
            } else {
                // 错误,此订单正在支付处理中.
                $ret['status'] = -1;
                $ret['message'] = "此订单正在支付处理中,请稍后,或联系客服";
                return $ret;
            }
        }

        $ret['status'] = 0;
        $ret['message'] = '付款凭证上传成功';
        $ret['trade'] = $one_trade;
        return $ret;
    }

    public function actionPaySuperDesigner() {
        if (Yii::$app->request->isPost) {
            $uid = Yii::$app->getUser()->identity->getId();
            $ret = array();
            $url_back = "https://app.jajahome.com/furniture/call_back_zfb_pay_vip.php";

            $tm = date('Ymdhis');
            $at = intval(rand(0,999999));
            $out_trade_no = $tm.$at;
            $money = 2000;
            $subject = "JAJAHOME 会员付年费 $money 元";
            LogPayVip::deleteAll(['and', ['trade_no' => $out_trade_no], ['not in', 'state', [1, 2]]]);
            $recordvip = new LogPayVip();
            $recordvip->prepay_id = $out_trade_no;
            $recordvip->transaction_id = "zfb_$out_trade_no";
            $recordvip->trade_no = $out_trade_no;
            $recordvip->user_type_class = 5;
            $recordvip->uid = $uid;
            $recordvip->type = 2;
            $recordvip->starttime = time();
            $recordvip->endtime = 0;
            $recordvip->memo_xml = '';
            $recordvip->rmb = $money;
            $recordvip->state = 0;
            $recordvip->state_count = 0;
            if (!$recordvip->save()) {
                $ret['status'] = -1;
                $ret['message'] = 'logpayvip表插入失败';
                return $this->render('submitSuccess', [
                    'redirectUrl' => Url::to(['account/apply-super-designer']),
                    'ret' => $ret,
                ]);
            }

            $this::alipay($money, $out_trade_no, $subject, $url_back);
        }
    }

    private function alipay($total_fee, $out_trade_no, $subject, $url_back = null , $body = null)
    {
        $url = Yii::$app->params['webPath'] . "gjj/vendor/alipay/pagepay/pagepay.php";
        $post_data = [
            "WIDout_trade_no" => $out_trade_no,
            "WIDsubject" => $subject,
            "WIDtotal_amount" => $total_fee,
            "WIDbody" => $body,
            'url_back' => $url_back
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        curl_close($ch);
        echo $result;

    }
}